import os

class TreeNode:
    def __init__(self, name, targets=set(), parent=None):
        self.name = name
        self.parent = parent  # 父节点
        self.children = {}
        self.targets = targets
        self.visit_flag = False

    def print_subtree(self, str="", indent=0):
        """
        打印当前节点下的全部目录层级
        """
        str += ' ' * indent + f"{self.name} - {self.visit_flag}\n"
        for child in self.children.values():
            str += child.print_subtree(indent = indent + 2)
        return str
    def add_child(self, child):
        """添加子节点"""
        self.children[child.name] = child
        child.parent = self

    def add_children_by_paths(self, children_path):
        """添加子节点"""
        if children_path:
            for child_path in children_path:
                try:
                    self.add_path(child_path)
                except ValueError as e:
                    print(e)
                    print(f"{child_path} 未加入目录树")
    def add_path(self, path):
        """
        增加指定路径
        """
        # 规范化路径：将路径分隔符统一为 "/"，并解析 "../"
        normalized_path = self._normalize_path(path)
        # 将路径拆分为列表
        path_parts = normalized_path.split("/") if normalized_path else []
        # 根据路径开头的 "../" 调整当前节点
        current_node = self._adjust_starting_node(path_parts)
        # 调用递归方法添加文件
        current_node._add_file_to_path_recursive(path_parts)

    def get_path_from_root(self):
        """
        获取从根目录到当前节点的路径
        :return: 路径字符串（例如 "root/dir1/dir2"）
        """
        path_parts = []
        current_node = self
        while current_node:
            path_parts.append(current_node.name)
            current_node = current_node.parent
        # 从根目录到当前节点，需要反转列表
        path_parts.reverse()
        path = "/".join(path_parts)
        return path

    def _normalize_path(self, path):
        # 统一路径分隔符为 "/"
        path = path.replace("\\", "/")
        # 拆分路径
        parts = path.split("/")
        stack = []
        for part in parts:
            if part and part != ".":  # 忽略 "." 和空字符串
                stack.append(part)
        # 重新拼接路径
        return "/".join(stack)

    def _adjust_starting_node(self, path_parts):
        """
        根据路径开头的 "../" 调整当前节点
        """
        current_node = self
        while path_parts and path_parts[0] == "..":
            if current_node.parent is None:
                raise ValueError("路径超出根目录范围")
            current_node = current_node.parent
            path_parts.pop(0)  # 移除已处理的 "../"
        return current_node

    def _add_file_to_path_recursive(self, path_parts):
        """
        递归方法：向指定路径添加文件
        """
        if len(path_parts) == 1:  # 如果路径为空，表示当前节点是目标路径
            try:
                if ":" not in path_parts[0]:
                    if '.' in path_parts[0]:
                        return
                    path_parts[0] = f'{path_parts[0]}:{path_parts[0]}'
                path, target = path_parts[0].split(":")
                if len(path) == 0:
                    self.targets.add(target)
                elif path in self.children:
                    self.children[path].targets.add(target)
                else:
                    self.add_child(TreeNode(name=path, targets=set([target])))
            except Exception as e:
                print(e)
                print(path_parts)
            return

        next_dir = path_parts[0]  # 获取路径的第一部分
        if next_dir.startswith("../"):
            print("............startswith../............")
        if next_dir not in self.children: # 如果子节点不存在，创建
            self.add_child(TreeNode(next_dir))
        # 递归进入下一层
        self.children[next_dir]._add_file_to_path_recursive(path_parts[1:])